package com.sicheng.lc.周赛.分类.图论.拓扑排序;

import java.util.*;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/6 16:10
 */
@SuppressWarnings("unused")
public class 从给定原材料中找到所有可以做出的菜 {
    //https://leetcode.cn/problems/find-all-possible-recipes-from-given-supplies/
    static ArrayList<String> res = new ArrayList<>(100);

    {
        res.clear();
    }

    public List<String> findAllRecipes(String[] recipes, List<List<String>> needs, String[] supplies) {

        ArrayList<Integer>[] g = new ArrayList[recipes.length];
        Arrays.parallelSetAll(g, k -> new ArrayList<>(20));

        HashSet<String> map = new HashSet<>(Arrays.asList(supplies));

        HashMap<String, Integer> index = new HashMap<>();
        for (int i = 0; i < recipes.length; i++) {
            index.put(recipes[i], i);
        }
        int[] degree = new int[recipes.length];
        for (int i = 0; i < recipes.length; i++) {
            List<String> need = needs.get(i);
            for (String s : need) {
                if (map.contains(s))
                    continue;
                int x = index.getOrDefault(s, -1);
                if (x < 0) {
                    // 如果需要的既不在原材料也不在食谱里，入度设为无穷大
                    degree[i] = Integer.MAX_VALUE;
                    continue;
                }
                g[x].add(i);
                degree[i]++;
            }
        }

        ArrayDeque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < degree.length; i++) {
            if (degree[i] == 0)
                deque.offer(i);
        }

        while (!deque.isEmpty()) {
            int x = deque.poll();
            for (int i : g[x]) {
                degree[i]--;
                if (degree[i] == 0)
                    deque.offer(i);
            }
        }
        for (int i = 0; i < degree.length; i++) {
            if (degree[i] == 0)
                res.add(recipes[i]);
        }
        return res;
    }


}
